#############################################
#Map of percentage voters with in-district volunteer
#############################################

rm(list = ls())

#Functions
source("functions.R")

#Packages
installPackageNotFound("RColorBrewer")
installPackageNotFound("rgdal")

#############################################
#Read in Voter data
#############################################

#All voters
all.voters <- read.csv("voters.csv", stringsAsFactors = F)

#VA District Shapefile
district.area <-readOGR("cb_2017_51_sldl_500k", "cb_2017_51_sldl_500k",
                       verbose = F)

#############################################
#Summarize proportion in district by district
#############################################

#Standardize district name
district.area@data$district_name <- as.numeric(district.area@data$SLDLST)

#District summary
district.summary <- aggregate(Volunteer_In_District~District,
                              data = all.voters, FUN = mean)

#Merge to shapefile
district.area@data$pct_in_district <-
  district.summary[match(district.area@data$district_name,
             district.summary$District), "Volunteer_In_District"]

#############################################
#Map
#############################################

#Color bins
district.area@data$prop_district <- cut(district.area@data$pct_in_district,
                                      c(0, 0.25, .50, .75, 1),
                                      #include.lowest = T,
                                      right = T)
#Color wheel
color.ramp <- brewer.pal(length(levels(district.area@data$prop_district)),
                         "YlOrRd")

#Color vector
color.vec <- color.ramp[as.numeric(district.area@data$prop_district)]
color.vec[is.na(color.vec)] <- "#f2f2f2"

par(mar=c(0,0.25,0,0.5),  mai = c(0,0,0,0), tcl=-0.3)

#Map
plot(district.area,
     col = color.vec,
     border = "#4d4d4d", lwd = 0.3)

legend(x=-82.7, y=36.5,
    legend = levels(district.area@data$prop_district),
    fill = color.ramp,
    bty = 'n',
    cex = 0.7,
    title = "Prop. voters with hyper-local volunteer", horiz=T)
